package com.atmilan.quartz.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XxlJobParamUtil {

    public static Map<String, String> getParams() {
        String param = XxlJobHelper.getJobParam();
        XxlJobHelper.log("接受参数:" + param);
        Map<String, String> res = new HashMap<>();
        if (StrUtil.isEmpty(param)) return res;
        param = StrUtil.cleanBlank(param);
        param = StrUtil.trim(param);
        List<String> pairList = StrUtil.splitTrim(param, '&');
        if (pairList.size() == 1) {
            res.put("_all", pairList.get(0));
            return res;
        }
        for (String pair : pairList) {
            List<String> pvs = StrUtil.splitTrim(pair, '=');
            if (pvs.size() == 1) {
                res.put(pvs.get(0), null);
            } else {
                res.put(pvs.get(0), pvs.get(1));
            }
        }
        return res;
    }

    public static Integer getInteger(Map<String, String> params, String key, Integer defVal) {
        String strVal = params.get(key);
        if (StrUtil.isEmpty(strVal)) return defVal;
        return Integer.parseInt(strVal);
    }

    public static String getAndCheckParam(Map<String, String> params, String key) {
        String strVal = params.get(key);
        if (StrUtil.isNotEmpty(strVal)) return strVal;
        strVal = params.get("_all");
        return strVal;
    }

    public static String getAndCheckParam(Map<String, String> params, String key, String defVal) {
        String val = getAndCheckParam(params, key);
        if (StrUtil.isEmpty(val)) return defVal;
        return val;
    }


}
